package com.gitee.qdbp.vmall.web.controller.sales.mgr.goods;

import java.util.List;
import java.util.Properties;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.model.paging.PageList;
import com.gitee.qdbp.able.model.reusable.EditResult;
import com.gitee.qdbp.able.result.ResponseMessage;
import com.gitee.qdbp.able.result.ResultCode;
import com.gitee.qdbp.able.utils.StringTools;
import com.gitee.qdbp.able.utils.VerifyTools;
import com.gitee.qdbp.base.model.condition.OrderPaging;
import com.gitee.qdbp.base.system.model.IAccount;
import com.gitee.qdbp.base.utils.EnumTools;
import com.gitee.qdbp.base.utils.SessionTools;
import com.gitee.qdbp.base.utils.WebFileHandler;
import com.gitee.qdbp.general.common.api.files.service.IWebFileService;
import com.gitee.qdbp.general.common.api.reusable.model.SimpleTreeBean;
import com.gitee.qdbp.general.common.api.reusable.model.SimpleTreeWhere;
import com.gitee.qdbp.general.common.api.reusable.service.ISimpleTreeQueryer;
import com.gitee.qdbp.general.system.api.personnel.service.IUserCoreQueryer;
import com.gitee.qdbp.tools.files.PathTools;
import com.gitee.qdbp.vmall.sales.api.goods.main.model.GoodsImages;
import com.gitee.qdbp.vmall.sales.api.goods.main.model.GoodsVersionBean;
import com.gitee.qdbp.vmall.sales.api.goods.main.model.GoodsVersionWhere;
import com.gitee.qdbp.vmall.sales.api.goods.main.model.PriceSingleParams;
import com.gitee.qdbp.vmall.sales.api.goods.main.model.PublishSingleParams;
import com.gitee.qdbp.vmall.sales.api.goods.main.model.QuantitySingleParams;
import com.gitee.qdbp.vmall.sales.api.goods.main.service.IGoodsVersionExecutor;
import com.gitee.qdbp.vmall.sales.api.goods.main.service.IGoodsVersionQueryer;
import com.gitee.qdbp.vmall.sales.enums.GoodsState;
import com.gitee.qdbp.vmall.sales.enums.MallScene;

/**
 * 商品基本信息控制器
 *
 * @author zhaohuihua
 * @version 170401
 */
@Controller
@RequestMapping("actions/goods/manager")
public class GoodsManageController {

    @Autowired
    @Qualifier("setting")
    private Properties setting;
    @Autowired
    private IWebFileService fileService;
    @Autowired
    private IUserCoreQueryer userCoreQueryer;
    @Autowired
    private IGoodsVersionQueryer goodsVersionQueryer;
    @Autowired
    private IGoodsVersionExecutor goodsVersionExecutor;
    @Autowired
    private ISimpleTreeQueryer simpleTreeQueryer;
    private WebFileHandler uploader;

    @PostConstruct
    private void init() {
        this.uploader = new WebFileHandler(fileService);
    }

    @ResponseBody
    @RequestMapping("preview-url")
    @RequiresPermissions("goods:manager:query")
    public ResponseMessage getPreviewUrl(String vid) {
        String prefix = setting.getProperty("site.h5.outer.url");
        String uri = setting.getProperty("goods.preview.uri");
        if (VerifyTools.isAnyBlank(prefix, uri)) {
            return new ResponseMessage(ResultCode.SERVER_INNER_ERROR);
        }

        String url = PathTools.concat(prefix, uri);
        return new ResponseMessage(StringTools.format(url, "vid", vid));
    }

    /** 查询商品列表 **/
    @ResponseBody
    @RequestMapping("list")
    @RequiresPermissions("goods:manager:query")
    public ResponseMessage listDuplicate(GoodsVersionWhere model, OrderPaging paging, Boolean extra,
            Boolean queryDuplicate) {
        IAccount operator = SessionTools.checkLoginUser();
        try {
            PageList<GoodsVersionBean> list = goodsVersionQueryer.list(model, paging);
            ResponseMessage result = new ResponseMessage(list.toList());
            if (Boolean.TRUE.equals(extra)) {
                result.addExtra(EnumTools.getEnumsResource(GoodsState.class));
                result.addExtra("User", userCoreQueryer.listByCreatorIds(list.toList(), operator));
                { // 查询分类列表
                    SimpleTreeWhere w =new SimpleTreeWhere();
                    OrderPaging p = OrderPaging.NONE;
                    PageList<SimpleTreeBean> category = simpleTreeQueryer.list(MallScene.GOODS_CATEGORY.name(), w, p);
                    result.addExtra("Category", category.toList());
                }
            }
            return result;
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 查询商品详情 **/
    @ResponseBody
    @RequestMapping("details")
    @RequiresPermissions("goods:manager:query")
    public ResponseMessage details(String vid, Boolean extra) {
        try {
            GoodsVersionBean bean = goodsVersionQueryer.findByVid(vid);
            if (bean == null) {
                return new ResponseMessage(ResultCode.RECORD_NOT_EXIST);
            }
            ResponseMessage result = new ResponseMessage(bean);
            if (Boolean.TRUE.equals(extra)) {
                result.addExtra(EnumTools.getEnumsResource(GoodsState.class));
                result.addExtra("CreatorUser", userCoreQueryer.find(bean.getCreatorId()));
            }
            return result;
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 保存草稿 **/
    @ResponseBody
    @RequestMapping("save-draft")
    @RequiresPermissions("goods:manager:edit")
    public ResponseMessage saveDraftOfCreate(GoodsVersionBean model, HttpServletRequest req) {
        try {
            IAccount operator = SessionTools.getLoginUser();

            List<String> urls = uploader.findAndUploadFiles(req, "image", "files");

            if (urls != null) {
                GoodsImages images = new GoodsImages();
                images.setDetails(urls);
                model.setImageInfo(images);
            }

            EditResult result = goodsVersionExecutor.save(model, operator);
            return new ResponseMessage(result);
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 创建副本 **/
    @ResponseBody
    @RequestMapping("create-duplicate")
    @RequiresPermissions("goods:manager:edit")
    public ResponseMessage createDuplicate(String vid) {

        try {
            IAccount operator = SessionTools.getLoginUser();

            GoodsVersionBean result = goodsVersionExecutor.createDuplicate(vid, operator);
            return new ResponseMessage(result);
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 提交审核 **/
    @ResponseBody
    @RequestMapping("submit")
    @RequiresPermissions("goods:manager:edit")
    public ResponseMessage submit(GoodsVersionBean model, String description, HttpServletRequest req) {

        try {
            IAccount operator = SessionTools.getLoginUser();

            List<String> urls = uploader.findAndUploadFiles(req, "image", "files");

            if (urls != null) {
                GoodsImages images = new GoodsImages();
                images.setDetails(urls);
                model.setImageInfo(images);
            }

            goodsVersionExecutor.submit(model, description, operator);
            return new ResponseMessage(model);
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 审批 **/
    @ResponseBody
    @RequestMapping("approve")
    @RequiresPermissions("goods:manager:approve")
    public ResponseMessage approve(String vid, boolean pass, String description) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            goodsVersionExecutor.approve(vid, pass, description, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 发布上架 **/
    @ResponseBody
    @RequestMapping("publish")
    @RequiresPermissions("goods:manager:publish")
    public ResponseMessage publish(PublishSingleParams params, String description) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            goodsVersionExecutor.publish(params, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 下架停售 **/
    @ResponseBody
    @RequestMapping("unpublish")
    @RequiresPermissions("goods:manager:unpublish")
    public ResponseMessage unpublish(String vid, String description) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            goodsVersionExecutor.unpublish(vid, description, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 删除新商品(从未发布上架过的) **/
    @ResponseBody
    @RequestMapping("delete-newer")
    @RequiresPermissions("goods:manager:delete:newer")
    public ResponseMessage deletePending(String vid, String description) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            goodsVersionExecutor.delete(vid, description, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 删除商品(曾经发布上架过的) **/
    @ResponseBody
    @RequestMapping("delete-selled")
    @RequiresPermissions("goods:manager:delete:selled")
    public ResponseMessage deleteSelled(String vid, String description) {

        // 曾经发布上架过的不能删除, 只是将版本状态改为归档, VersionState.ENDED
        try {
            IAccount operator = SessionTools.getLoginUser();
            goodsVersionExecutor.delete(vid, description, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 补充库存 **/
    @ResponseBody
    @RequestMapping("change-stock-quantity")
    @RequiresPermissions("goods:manager:change:stock-quantity")
    public ResponseMessage updateStockQuantity(QuantitySingleParams params, String description) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            goodsVersionExecutor.updateStockQuantity(params, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 调整销量 **/
    @ResponseBody
    @RequestMapping("change-sales-quantity")
    @RequiresPermissions("goods:manager:change:sales-quantity")
    public ResponseMessage updateSalesQuantity(QuantitySingleParams params, String description) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            goodsVersionExecutor.updateSalesQuantity(params, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 修改价格(只允许修改未发布上架的商品) **/
    @ResponseBody
    @RequestMapping("edit-price")
    @RequiresPermissions("goods:manager:edit")
    public ResponseMessage editPrice(PriceSingleParams params) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            EditResult result = goodsVersionExecutor.editPrice(params, operator);
            return new ResponseMessage(result);
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 调整价格(已发布上架的商品, 生成新的副本, 并直接将新的副本发布上架) **/
    @ResponseBody
    @RequestMapping("change-price")
    @RequiresPermissions("goods:manager:change:price")
    public ResponseMessage changePrice(PriceSingleParams params) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            EditResult result = goodsVersionExecutor.changePrice(params, operator);
            return new ResponseMessage(result);
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }
}
